package fishlord;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

class Pool extends JPanel {
	
	BufferedImage background = null;	// 游戏界面的背景图片
	Fish fish = null;    				// 鱼
	Fish[] fishs = new Fish[11];		// 鱼对象数组
	Net net = null;						// 渔网
	
	int score = 0;						// 分数
	Font font = new Font("楷体", Font.BOLD, 20);//BOLD字体加粗

	public  Pool() throws IOException {//抛去IO流异常
		
		// 读取src/images包下的资源文件
		background = ImageIO.read(getClass().getResourceAsStream("/images/bg.jpg"));
		
		//产生11条鱼，每1条鱼都是1个线程
		for (int i = 0; i < 11; i++) {
			if (i < 9) {
				fish = new Fish("fish0" + (i + 1));
			} else {
				fish = new Fish("fish" + (i + 1));
			}
			
			fishs[i] = fish;
			new Thread(fish).start();
		}
	}

	@Override
	public void paint(Graphics g) {
		
		g.drawImage(background, 0, 0, null); 												// 绘制背景
		for (int i = 0; i < fishs.length; i++) {
			Fish tempfish = fishs[i];
			g.drawImage(tempfish.fishImage, tempfish.x, tempfish.y, null); 					// 绘制鱼
		}
		if (net.show) {
			g.drawImage(net.netImage, net.x - net.width / 2, net.y - net.height / 2, null); // 判断渔网是否显示，绘制渔网
		}
		g.setFont(font);
		g.setColor(Color.YELLOW);
		if(score<1000) {
			g.drawString("SCORE:", 10, 20);
			g.setColor(Color.RED);
			g.drawString("      " + score, 10, 20);
		}
		else{
			g.drawString("游戏通过!",10,20);
		}
	}

	//实现点击鼠标进行捕鱼
	public void action() throws Exception {//抛去异常

		net = new Net();
		
		MouseAdapter adapter = new MouseAdapter() {
			
			//鼠标进入，渔网显示；鼠标移出，渔网不显示
			@Override
			public void mouseEntered(MouseEvent e) {
				net.show = true;
			}

			@Override
			public void mouseExited(MouseEvent e) {
				net.show = false;
			}

			//渔网的位置随着鼠标的位置变化
			@Override
			public void mouseMoved(MouseEvent e) {
				
				net.x = e.getX();
				net.y = e.getY();
			}

			//当鼠标按下的时候进行捕鱼操作
			@Override
			public void mousePressed(MouseEvent e) {
				catchFish();
			}

		};
		
		this.addMouseListener(adapter); 		// 添加鼠标监听器
		this.addMouseMotionListener(adapter);	// 鼠标移动监听器

		while (true) {
			repaint();
			try {
				Thread.sleep(100); 				// 每隔一定时间刷新屏幕
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	//渔网是否捉到鱼
	protected void catchFish() {
		// 鱼在不在网的范围内？在的话就让鱼消失
		for (int i = 0; i < fishs.length; i++) {
			fish = fishs[i];
			if (fish.fishInNet(net.x, net.y)) {// 判断在不在网的范围
				fish.goInPool();				 // 鱼从池子中消失，重新从右边游入	
				score += fish.width / 10;// 不同的鱼有不同的分数
			}
		}
	}

}